package key

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

type Monster struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Skill string `json:"skill"`
}

// Store 序列化存储
func (this *Monster) Store() bool {
	// 先进行序列化，后保存至文件
	data, err := json.Marshal(this)
	if err != nil {
		fmt.Printf("when order are serializing，err=%v\n", err)
		return false
	}

	filePath := "../other/serialize.txt"
	err = ioutil.WriteFile(filePath, data, 0666)

	if err != nil {
		fmt.Printf("when order are writing err=%v\n", err)
		return false
	}

	return true
}

func (this *Monster) ReStore() bool {
	filePath := "../other/serialize.txt"
	data, err := ioutil.ReadFile(filePath)

	if err != nil {
		fmt.Printf("when order are reading err=%v\n", err)
		return false
	}

	err = json.Unmarshal(data, this)
	if err != nil {
		fmt.Printf("when order are unserializing err=%v\n", err)
		return false
	}

	return true
}
